<?php

namespace App\Models\Shop;

use App\Libraries\Tools\ConstVar;
use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShopCouponPurchase extends BaseModel
{


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'updated_at'
    ];

    protected $dateFormat = 'U';

    /**
     * 新增商家套餐购买记录
     * @param $user_id
     * @param $coupon_id
     * @param $shop_id
     * @param $price
     * @param $type
     * @param int $order_id
     * @param int $status
     * @return mixed
     */
    public function add($user_id, $coupon_id, $shop_id, $price, $type, $order_id=0, $status=6){
        $this->user_id = $user_id;
        $this->shop_id = $shop_id;
        $this->coupon_id = $coupon_id;
        $this->order_id = $order_id;
        $this->status = $status;
        $this->amount = $price;
        $this->type = $type;
        $coupon = ShopCoupon::find($coupon_id);
        $this->title = $coupon->title;
        $this->content = $coupon->content;
        $this->cover = $coupon->cover;
        $this->price = $coupon->price;
        $this->rec_num = $coupon->rec_num;
        $this->start_at = $coupon->start_at;
        $this->end_at = $coupon->end_at;
        $this->save();
        $code = rand(99999, 999999);
        $this->code = $code . $this->id;
        $this->save();
        return $this->id;
    }

    /**
     * 根据code获取详情
     * @param $code
     * @return mixed
     */
    public function getPurchaseByCode($code){
        $data = $this->with('coupon')
            ->withOnly('order', ['id', 'channel', 'total_amount', 'receipt_amount'])
            ->where('code', $code)
            ->first();
        return $this->after($data);
    }

    /**
     * 根据code获取详情V2
     * @param $code
     * @return mixed
     */
    public function getPurchaseByCodeV2($code){
        $data = $this->with('shop')
            ->withOnly('order', ['id','channel','total_amount','receipt_amount','hong_bao_amount'])
            ->where('code', $code)
            ->first();
        return $this->after($data);
    }

    /**
 * 获取purchase列表
 * @param $page
 * @param $size
 * @param null $start_at
 * @param null $end_at
 * @param null $status
 * @param null $shop_id
 * @return mixed
 */
    public function getPurchases($page, $size, $start_at=null, $end_at=null, $status=null, $shop_id=null){
        $data = [];
        $sql = $this->with('coupon')
            ->with('shop')
            ->withOnly('user', ['user_id', 'nickname', 'cover'])
            ->withOnly('order', ['id', 'channel', 'total_amount', 'receipt_amount'])
            ->where('status','<>',6);
        if(isset($status)){
            $sql = $sql->whereIn('status', $status);
        }
        if(isset($shop_id)){
            $sql = $sql->where('shop_id', $shop_id);
        }else{
            $sql = $sql->where('user_id', Auth::id());
        }
        if(isset($start_at) && isset($end_at)){
            $sql = $sql->whereBetween('verify_at', [$start_at, $end_at]);
        }
        $data['list'] = $sql->orderBy('id', 'desc')
            ->forPage($page, $size+1)
            ->get()
            ->toArray();
        $data['next_page'] = $page + 1;
        $data['page_size'] = $size;

        return $this->after($data);
    }

    /**
     * 获取已购买purchase列表V2
     * @param $page
     * @param $size
     * @param null $start_at
     * @param null $end_at
     * @param null $status
     * @param null $shop_id
     * @return mixed
     */
    public function getPurchasesV2($page, $size, $start_at=null, $end_at=null, $status=null, $shop_id=null){
        $data = [];
        $sql = $this->with('shop')
            ->withOnly('user', ['user_id', 'nickname', 'cover'])
            ->withOnly('order', ['id','channel','total_amount','receipt_amount','hong_bao_amount'])
            ->where('status','<>',6);
        if(isset($status)){
            $sql = $sql->whereIn('status', $status);
        }
        if(isset($shop_id)){
            $sql = $sql->where('shop_id', $shop_id);
        }else{
            $sql = $sql->where('user_id', Auth::id());
        }
        if(isset($start_at) && isset($end_at)){
            $sql = $sql->whereBetween('verify_at', [$start_at, $end_at]);
        }
        $data['list'] = $sql->orderBy('id', 'desc')
            ->forPage($page, $size+1)
            ->get()
            ->toArray();
        $data['next_page'] = $page + 1;
        $data['page_size'] = $size;

        return $this->after($data);
    }

    /**
     * 经营数据
     * @param $id
     * @param $request
     * @return mixed
     */
    public function businessData($id, $request){
		if($request['type'] == 1){
			$time = 'shop_coupon_purchases.created_at';
		}else{
			$time = 'shop_coupon_purchases.verify_at';
		}
        if($request['date_type'] == 1){
            $time_format = '%Y-%m-%d';
        }else{
            $time_format = '%Y-%m';
        }

        $data['total_purchases'] = $this->where('shop_id', $id)->count();
        $data['total_balance'] = $this->where('shop_id', $id)->sum('amount');
        $data['total_verify_purchases'] = $this->where('shop_id', $id)
            ->where('verify_at', '!=', 0)
            ->count();
        $data['total_verify_balance'] = $this->where('shop_id', $id)
            ->where('verify_at', '!=', 0)
            ->sum('amount');
//        $data['refund_purchases'] = $this->where('shop_id', $id)->where('status', 4)->count();
//        $data['refund_balance'] = $this->where('shop_id', $id)->where('status', 4)->sum('amount');
//        $data['each_coupon'] = $this->selectRaw('coupon_id, count(1) as num, sum(amount) as balance')
//            ->withOnly('coupon', ['id', 'title'])
//            ->where('shop_id', $id)
//            ->groupBy('coupon_id')
//            ->get();

        $data['on_date'] = DB::select("SELECT DATE_FORMAT(FROM_UNIXTIME({$time}), '{$time_format}') AS `date`,
            COUNT(1) AS num, SUM(shop_coupon_purchases.amount) AS balance
            FROM shop_coupon_purchases shop_coupon_purchases
            WHERE shop_coupon_purchases.shop_id={$id}
            AND {$time} BETWEEN {$request['start_at']} AND {$request['end_at']}
            GROUP BY DATE_FORMAT(FROM_UNIXTIME({$time}), '{$time_format}')");
        foreach($data['on_date'] as &$v){
            $v->each_coupon = $this->selectRaw('coupon_id, count(1) AS num, SUM(amount) AS balance')
                ->withOnly('coupon', ['id', 'title'])
                ->where('shop_id', $id)
                ->whereRaw("DATE_FORMAT(FROM_UNIXTIME({$time}), '{$time_format}')='{$v->date}'")
                ->groupBy('coupon_id')
                ->get();
            $v->refund_purchases = $this->where('shop_id', $id)
                ->where('status', ConstVar::$PURCHASE_STATUS_REFUNDED)
                ->whereRaw("DATE_FORMAT(FROM_UNIXTIME(updated_at), '{$time_format}')='{$v->date}'")
                ->count();
            $v->refund_balance = $this->where('shop_id', $id)
                ->where('status', ConstVar::$PURCHASE_STATUS_REFUNDED)
                ->whereRaw("DATE_FORMAT(FROM_UNIXTIME(updated_at), '{$time_format}')='{$v->date}'")
                ->sum('amount');
        }
        return $data;
    }

    /**
     * 关联套餐
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function coupon(){
        return $this->hasOne('App\Models\Shop\ShopCoupon', 'id', 'coupon_id');
    }

    /**
     * 关联商家
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function shop(){
        return $this->hasOne('App\Models\Shop\Shop', 'shop_id', 'shop_id');
    }

    /**
     * 关联支付订单
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function order(){
        return $this->hasOne('App\Models\Order\Order', 'id', 'order_id');
    }

    /**
     * 关联用户
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function user(){
        return $this->hasOne('App\Models\User\User', 'user_id', 'user_id');
    }
}
